package com.sojson.config.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.sojson.util.ThreadLocalUtil;
import com.sojson.util.servlet.ServletUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求过滤器
 *
 * @author liu
 * @date 2022-01-17
 */
@Slf4j
public class RequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        // 设置字符集
        ServletUtil.initCharacterEncoding(request, response);
        // 初始化响应头
        ServletUtil.initServletResponse(response);

        int size = ThreadLocalUtil.HANDLERS.size();
        try {
            for (int i = 0; i < size; i++) {
                ThreadLocalUtil.HANDLERS.get(i).run();
            }

            chain.doFilter(request, response);
        } finally {
            for (int i = size - 1; i > -1; i--) {
                try {
                    ThreadLocalUtil.HANDLERS.get(i).finallys();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

}